package weibo.network;

import com.google.gson.Gson;
import com.whu.zj.MyApplication;
import com.whu.zj.R;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.util.List;

import weibo.dto.BlogData;

/**
 * 发送微博
 * Created by Administrator on 2016/3/31.
 */
public class SendWeibo {

    BlogData blogData;

    List<File> files;

    public void setBlogData(BlogData blogData) {
        this.blogData = blogData;
    }

    public void setFiles( List<File> files) {
        this.files = files;
    }

    // 上传
    public boolean upload() throws Exception {
        HttpClient httpClient = new DefaultHttpClient();
        String IP = MyApplication.share().getResources().getString(R.string.IP);
        String url = "http://" + IP + "/SendWeBlog";
        HttpPost post = new HttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        Gson gson = new Gson();
        builder.addTextBody("data", gson.toJson(blogData), ContentType.TEXT_PLAIN.withCharset("utf-8"));
        long time = System.currentTimeMillis();
        for (int i = 0; i < files.size(); i++) {
            builder.addBinaryBody(time + "_"+files.get(i).getName(),files.get(i), ContentType.APPLICATION_OCTET_STREAM,time + "_"+files.get(i).getName());
        }
        HttpEntity entity = builder.build();
        post.setEntity(entity);
        HttpResponse response = httpClient.execute(post);

        if (response.getStatusLine().getStatusCode() == 200) {
            System.out.println("HttpUrlUpload(uploadFile)文件上传成功！！！");
            return true;
        }
        System.out.println("HttpUrlUpload(uploadFile)文件上传失败！！！");
        return false;
    }
}
